﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Practices.Prism.ViewModel;

namespace Data
{
    public class GameManager : NotificationObject
    {
        private string settingsFileName = "settings.xml";

        #region Interface

        #region LoadGames

        public ObservableCollection<Game> LoadGames()
        {
            Load();
            return new ObservableCollection<Game>(Games);
        }

        #endregion

        #region SaveGames

        public void SaveGames(ObservableCollection<Game> gamesToSave )
        {
            Games = gamesToSave.ToList();
            Save();
        }

        #endregion

        #region SaveSettings

        public void SaveSettings(Settings settingsToSave = null)
        {
            Settings = settingsToSave ?? Settings;
            Save();
        }

        #endregion

        #endregion

        #region Helpers

        #region Load
        private void Load()
        {
            if (!File.Exists(settingsFileName))
            {
                SaveGames(new ObservableCollection<Game>());
            }

            var deserializer = new XmlSerializer(typeof(GameManager));
            using (var textReader = new StreamReader(settingsFileName))
            {
                var settings = (GameManager)deserializer.Deserialize(textReader);
                if (settings != null)
                {
                    Games = settings.Games;
                    Settings = settings.Settings;
                }
                textReader.Close();
            }
        }
        #endregion

        #region Save

        private void Save()
        {
            var serializer = new XmlSerializer(typeof(GameManager));
            using (var textWriter = new StreamWriter(settingsFileName))
            {
                serializer.Serialize(textWriter, this);
                textWriter.Close();
            }
        }

        #endregion

        #endregion

        #region Properties

        #region Settings

        public Settings Settings
        {
            get {
                return settings ?? (settings = new Settings()); }
            set
            {
                if (settings != value)
                {
                    settings = value;
                    RaisePropertyChanged(() => Settings);
                }
            }
        }

        private Settings settings;

        #endregion

        #region Games

        public List<Game> Games { get; set; }

        #endregion

        #endregion
    }
}
